<?php

namespace App\Imports;

use App\Models\User\LiPei;
use App\Models\User\LiPeiSum;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;

class LiPeiImport implements ToCollection
{

    public $msg;
    public $account;


    public function __construct($account) {
        $this->account = $account;
    }

    public function collection(Collection $collection) {

        $info = [];
        $time = date('Y-m-d H:i:s');
        $import_number = uniqid();
        foreach ($collection as $k=>$v) {
            if($k<=0)continue;
            $info[] = [
                'import_number'=>$import_number,
                'case_number'=>$v[0],
                'bao_dan_number'=>$v[1],
                'toubao_name'=>$v[2],
                'baoxian_name'=>$v[3],
                'chu_xian_date'=>$v[4],
                'chu_xian_place'=>$v[5],
                'car_number'=>$v[6],
                'reason'=>$v[7],
                'loss_price'=>$v[8],
                'is_cancel_case'=>$v[9],
                'created_at'=>$time,
                'updated_at'=>$time,
                'account'=>$this->account
            ];
        }

        //导入前，先把之前导入的数据清理

        $caseNumbers = array_column($info, 'case_number');
        try{
            DB::beginTransaction();

            LiPei::whereIn('case_number',$caseNumbers)->forceDelete();
            LiPei::insert($info);

            LiPeiSum::updateOrCreate(['import_number'=>$import_number],[
                'account'=>$this->account,
                'records_count'=>count($info),
                'import_number'=>$import_number,
            ]);


            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            $this->msg = $tip;
            Log::error($tip);
            return;
        }

        Artisan::call('check:auto');


    }
}
